import { useEffect, useRef, useState } from 'react'
import Content from './Content'
import Header from './Header'
import FilterResult from './Result'
import './style/index.less'

/**
 * 1、图片和文件先缓存在本地，项目提供外网可访问文件服务器时，将图片和文件上传到文件服务器使用
 * 2、说明文档数量增多后做查询优化可以把文档入库
 */
export type ManualType = {
  title: string
  path: string
  content: string
}

const manualList: ManualType[] = [
  {
    title: '智算服务平台是什么？',
    path: 'https://viu-lpsdk.oss-cn-hangzhou.aliyuncs.com/agent_platform/manual/manual1.md',
    content: ''
  },
  {
    title: '创建你的智能体（智能体）',
    path: 'https://viu-lpsdk.oss-cn-hangzhou.aliyuncs.com/agent_platform/manual/manual2.md',
    content: ''
  },
  {
    title: '上线你的智能体（智能体）',
    path: 'https://viu-lpsdk.oss-cn-hangzhou.aliyuncs.com/agent_platform/manual/manual3.md',
    content: ''
  },
  {
    title: '如何使用提示词？',
    path: 'https://viu-lpsdk.oss-cn-hangzhou.aliyuncs.com/agent_platform/manual/manual4.md',
    content: ''
  },
  {
    title: '如何使用知识库？',
    path: 'https://viu-lpsdk.oss-cn-hangzhou.aliyuncs.com/agent_platform/manual/manual5.md',
    content: ''
  },
  {
    title: '如何使用插件？',
    path: 'https://viu-lpsdk.oss-cn-hangzhou.aliyuncs.com/agent_platform/manual/manual6.md',
    content: ''
  },
  {
    title: '如何使用工作流？',
    path: 'https://viu-lpsdk.oss-cn-hangzhou.aliyuncs.com/agent_platform/manual/manual7.md',
    content: ''
  }
]
/**
 * 使用指南
 * @param props
 * @returns
 */
const UserManual = (props: any) => {
  const [title, setTitle] = useState(manualList[0].title)
  const manualListRef = useRef(manualList)
  const activeManual = manualListRef.current.find(item => item.title === title)

  useEffect(() => {
    if (!manualList[0].content) {
      Promise.all(
        manualList.map(manual =>
          fetch(manual.path)
            .then(res => res.text())
            .then(text => ({ title: manual.title, path: manual.path, content: text }))
        )
      ).then(loadedFiles => {
        manualListRef.current = loadedFiles
      })
    }
  }, [1000])

  const [query, setQuery] = useState('')
  const handleSearch = keyword => {
    console.log('handleSearch', keyword)
    setQuery(keyword)

    if (keyword) {
      const filteredResults = manualListRef.current.filter(manual => manual.content.includes(keyword))
      setResults(filteredResults)
    } else {
      setResults([])
    }
  }
  const lastEvent = useRef(null)
  const handleBeforeSearch = keyword => {
    setQuery(keyword)
    lastEvent.current = keyword
  }
  useEffect(() => {
    let timeoutId = null
    const debouncedChange = () => {
      if (lastEvent.current) {
        handleSearch(query)
        lastEvent.current = null
      }
    }

    timeoutId = setTimeout(debouncedChange, 1000)

    return () => {
      clearTimeout(timeoutId)
    }
  }, [query])

  const [results, setResults] = useState<ManualType[]>([])

  const handleResultClick = title => {
    console.log('handleResultClick', title)
    setQuery('')
    setTitle(title)
  }

  return (
    <div className="user-manual">
      <Header query={query} handleSearch={handleBeforeSearch}></Header>
      <div className="user-main">
        <div className="left">
          <div className="title-container">
            <div className="title">使用指南</div>
          </div>
          <div className="list-container">
            {manualList.map(manual => {
              return (
                <div
                  className="list-item"
                  key={manual.title}
                  style={{ background: title === manual.title ? '#f5f7fa' : '#ffffff' }}
                  onClick={() => {
                    setTitle(manual.title)
                    setQuery('')
                  }}
                >
                  {manual.title}
                </div>
              )
            })}
          </div>
        </div>
        <div className="right">
          {query ? (
            <FilterResult query={query} resultList={results} handleResultClick={handleResultClick} />
          ) : (
            <Content manual={activeManual} />
          )}
        </div>
      </div>
    </div>
  )
}

export default UserManual
